﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApp.Models;
using Facebook;

namespace WebApp.Controllers
{
    public abstract class ApplicationController : Controller
    {
        private String authToken = null;
        private String id = "me";

        public String AuthToken
        {
            get { return authToken; }
        }

        public String Id
        {
            get { return id; }
        }

        /// <summary>
        /// Called before any action is called
        /// </summary>
        /// <param name="context"></param>
        override protected void OnActionExecuting(
            ActionExecutingContext context)
        {
            if (HttpContext.Request.QueryString["id"] != null)
            {
                id = HttpContext.Request.QueryString["id"].ToString();
            }
            else
            {
                id = "me";
            }
            ViewData["Id"] = Id;
            if (HttpContext.Session["authToken"] != null)
            {
                try
                {
                    authToken = HttpContext.Session["authToken"].ToString();
                    Person.Ref person = new Person.Ref(Id);
                    person.Populate(authToken);
                    ViewData["ProfileModel"] = person;
                    Person.Ref me = new Person.Ref("me");
                    me.Populate(authToken);
                    ViewData["MyProfile"] = me;
                }
                catch (Exception e)
                {
                }
            }
            if (HttpContext.Request.Form["authToken"] != null)
            {
                try
                {
                    authToken = HttpContext.Request.Form["authToken"].ToString();
                    Person.Ref person = new Person.Ref(Id);
                    person.Populate(authToken);
                    ViewData["ProfileModel"] = person;
                }
                catch (Exception e)
                {
                }
            }
        }

        public static bool IsMe(ViewDataDictionary viewData)
        {
            return viewData["Id"].Equals("me");
        }
    }
}
